# Apply to: sfbos_1.csv
# Description: W-NOMINATE of San Francisco Supervisors

# Remove all objects just to be safe

rm(list=ls(all=TRUE))


# Load appropriate packages

# Standard

library(MASS)
library(stats)


# W-NOMINATE

library(pscl)
library(wnominate)
library(gdata)
library(ellipse)

# Read in data

sfbos1 <- read.table(".../1805 Roadmaps/Figures A5 and A6/sfbos_1.csv", header=TRUE, sep=",")

dim(sfbos1)

head(sfbos1[,1:15])


## Format data

sfbos <- as.vector(sfbos1)
sfbos.2 <- sfbos[,-c(1,2,3,4)]
sfbos.names <- sfbos[,2]
legData <- matrix(sfbos[,4], length(sfbos[,4]),1)


## Create rollcall object

rc <- rollcall(data=sfbos.2, yea=c(1), nay=c(6), missing=c(9), notInLegis=0,
               legis.names=sfbos.names,
               legis.data=legData,
               desc="SF BoS Votes 2009-2011", source="sfbos.gov")


# Run WNOMINATE
# Supervisor Michela Alioto-Pier used to define polarity

set.seed(563223)

result <- wnominate(rcObject=rc, polarity=c(1,1))

summary(result)


# Assume 1-D model

set.seed(2345667)

result1 <- wnominate(rcObject=rc, polarity=c(1), dim=1)


# Write ideal points to file

scores <- result1$legislators
write.csv(scores, ".../1805 Roadmaps/Figures A5 and A6/sfbos_1_scores.csv")
save.image(".../1805 Roadmaps/Figures A5 and A6/sfbos_1_scores.RData")

eigen <- result1$eigenvalues
write.csv(eigen, ".../1805 Roadmaps/Figures A5 and A6/sfbos_1_eigen.csv")


# Clean up

# rm(list=ls(all=TRUE))

# End
